<?php
namespace app\common\service\impl;
use app\common\service\SecureService;
use app\common\model\Secure;
use think\facade\Log;
use app\common\model\Cars;
use app\common\exception\ZeduException;
use app\common\enums\ResultEnum;
use app\common\model\SecureFile;
use app\common\utils\OssFlies;
use app\common\validate\SecureValidate;

class SecureServiceImpl implements SecureService
{
    protected $secure;
    protected $cars;
    protected $secureFile;
    protected $secureValidate;
    protected $ossFiles;
    
    public function __construct(Secure $secure,Cars $cars,SecureFile $secureFile,SecureValidate $secureValidate,OssFlies $ossFiles)
    {
        $this->secure = $secure;
        $this->cars = $cars;
        $this->secureFile = $secureFile;
        $this->secureValidate = $secureValidate;
        $this->ossFiles = $ossFiles;
    }
    
    public function index(array $where, int $length, int $page)
    {
        try {
            $model = Secure::with(['cars'=>['agency','brand']])->where($where)->order('status asc,warn desc,id desc')
            ->paginate($length,false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$page,
            ]);
            
        } catch (\Exception $e) {
            Log::record('[ 投保列表 ]:'.$e->getMessage(),'error');
            return false;
        }
        return $model;
    }
    
    public function save(array $data)
    {
        $data['car_id'] = $this->cars->where(['car_sn'=>$data['car_sn']])->value('car_id');

        if(empty($data['car_id'])){
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>'车牌号不存在']);
        }
        $data['secure_start'] = strtotime($data['secureStart']);
        $data['secure_end'] = strtotime($data['secureEnd']);
        if($data['secure_end']<time()){
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>'到期日不能小于今日']);
        }
        $where = [];
        $where[] = ['car_id','=',$data['car_id']];
        $where[] = ['secure_type','=',$data['secure_type']];
        $where[] = ['secure_end','<= time',$data['secure_end']];
        $where[] = ['status','=',1];
        $where[] = ['notice','=',1];
        try {
            $secureId= $this->secure->where($where)->value('id');
            
        } catch (\Exception $e) {
            Log::record('[ 查找投保车辆 ]:'.$e->getMessage(),'error');
            return false;
        }

        if($secureId){
            try {
                $secure = $this->secure->create($data,true);
            } catch (\Exception $e) {
                Log::record('[ 添加记录 ]:'.$e->getMessage(),'error');
                return false;
            }
            
            try {
                $this->secure->update(['status'=>2,'notice'=>2,'warn'=>2],['id'=>$secureId]);
            } catch (\Exception $e) {
                Log::record('[ 更新状态 ]:'.$e->getMessage(),'error');
                return false;
            }
            
        }else{
            try {
                $secure = $this->secure->create($data,true);
            } catch (\Exception $e) {
                Log::record('[ 添加记录 ]:'.$e->getMessage(),'error');
                return false;
            }
        }
        
       /*  if (!$this->secureValidate->check($data)) {
            throw new ZeduException(['code'=>ResultEnum::ERROR['code'],'msg'=>$this->secureValidate->getError()]);
        } */
        
        
        if(!empty($data['secure_file'])){
            foreach ($data['secure_file'] as $value){
                try {
                    $this->secureFile->create(['secure_id'=>$secure->id,'file_url'=>$value]);
                } catch (\Exception $e) {
                    Log::record('[ 保存图片 ]:'.$e->getMessage(),'error');
                    return false;
                }
            } 
        }
        
        return true; 
        
    }
    
    public function list(int $id)
    {
        try {
            $data = $this->secure->with('cars')->get($id);
            $data['secure_file'] = $this->secureFile->where(['secure_id'=>$id])->field('file_url')->select();
        } catch (\Exception $e) {
            Log::record('[ 查询数据 ]:'.$e->getMessage(),'error');
            return false;
        }
        return $data;
    }
    
    public function edit(array $data)
    {
        
        $data['car_id'] = $this->cars->where(['car_sn'=>$data['car_sn']])->value('car_id');
        
        if(empty($data['car_id'])){
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>'车牌号不存在']);
        }
        
        $data['secure_start'] = strtotime($data['secureStart']);
        $data['secure_end'] = strtotime($data['secureEnd']);
        if($data['secure_end']<time()){
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>'到期日不能小于今日']);
        }
        try {
            $this->secure->allowField(true)->isUpdate(true)->save($data,['id'=>$data['id']]);
        } catch (\Exception $e) {
            Log::record('[ 更新数据 ]:'.$e->getMessage(),'error');
            return false;
        }
        
        if(!empty($data['secure_file'])){
            foreach ($data['secure_file'] as $value){
                try {
                    $this->secureFile->create(['secure_id'=>$data['id'],'file_url'=>$value]);
                } catch (\Exception $e) {
                    Log::record('[ 保存图片 ]:'.$e->getMessage(),'error');
                    return false;
                }
            }
        }
        
        return true; 
        
    }
    
    public function delFile(String $url)
    {
        $this->secure->startTrans();
        try {
            $object = 'record/uploads/'.$url;
            $data = $this->ossFiles->unlinkOss($object);
           
        } catch (\Exception $e) {
            Log::record('[ oss删除图片失败 ]:'.$e->getMessage(),'error');
            $this->secure->rollback();
            return false;
        }
        
        if($data){
            try {
                $this->secureFile->where(['file_url'=>$url])->delete();
                $this->secure->commit();
            } catch (\Exception $e) {
                Log::record('[ secure_file删除图片失败 ]:'.$e->getMessage(),'error');
                $this->secure->rollback();
                return false;
            }   
        }
        return true;
    }
    
    public function upload(array $data)
    {
        $uploadData = [];
        $insertNum = 0;
        if(!empty($data)){
            foreach ($data as $value) { 
                $uploadData['car_sn'] = trim($value[0]??'');
                switch (trim($value[1]??'')) {
                    case '交强险':
                        $uploadData['secure_type'] = 1;
                        break;
                    case '商业保险':
                        $uploadData['secure_type'] = 2;
                        break;
                    case '承运人责任险':
                        $uploadData['secure_type'] = 3;
                        break;
                    default:
                        throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>$value[1].'不存在']);
                }
                
                switch (trim($value[2]??'')) {
                    case '平安保险':
                        $uploadData['secure_company'] = 1;
                        break;
                    case '阳光保险':
                        $uploadData['secure_company'] = 2;
                        break;
                    case '中银保险':
                        $uploadData['secure_company'] = 3;
                        break;
                    case '中保保险':
                        $uploadData['secure_company'] = 4;
                        break;
                    case '中华联合保险':
                        $uploadData['secure_company'] = 5;
                        break;
                    case '太平洋保险':
                        $uploadData['secure_company'] = 6;
                        break;
                    case '都邦财产保险':
                        $uploadData['secure_company'] = 7;
                        break;
                    case '中国人寿保险':
                        $uploadData['secure_company'] = 8;
                        break;
                    case '永安保险':
                        $uploadData['secure_company'] = 9;
                        break;
                    default:
                        throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>$value[2].'不存在']);
                }
                if( is_numeric($value[3]??'') ){
                    $uploadData['secure_start'] = date('Y-m-d',($value[3]-25569)*24 * 60 * 60);
                }else{
                    $star = $value[3]??'';
                    if( is_object($star) ){
                        
                        $uploadData['secure_start'] = $star->__toString();
                    }else{
                        $uploadData['secure_start'] = $star;
                    }
                }
                if(is_numeric($value[4]??'')){
                    $uploadData['secure_end'] = date('Y-m-d',($value[4]-25569)*24 * 60 * 60);
                }else{
                    $end = $value[4]??'';
                    if( is_object($end) ){
                        
                        $uploadData['secure_end'] = $end->__toString();
                    }else{
                        $uploadData['secure_end'] = $end;
                    }
                }
                $uploadData['secure_money'] = floatval($value[5]??'');
                $uploadData['secure_desc'] = trim($value[6]??'');
                $res = $this->saveUpload($uploadData);
                if($res){
                    $insertNum++;
                }
            }
            
            return $insertNum;
        }
    }
    
    public function saveUpload($data){
        $data['car_id'] = $this->cars->where(['car_sn'=>$data['car_sn']])->value('car_id');
        
        if(empty($data['car_id'])){
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>$data['car_sn'].'车牌号不存在']);
        }
      
        if(strtotime($data['secure_end'])<time()){
            throw new ZeduException(['code'=>ResultEnum::FIND_ERROR['code'],'msg'=>'失效日期不能小于今日']);
        }
        $where = [];
        $where[] = ['car_id','=',$data['car_id']];
        $where[] = ['secure_type','=',$data['secure_type']];
        $where[] = ['secure_end','<= time',$data['secure_end']];
        $where[] = ['status','=',1];
        $where[] = ['notice','=',1];
        try {
            $secureId= $this->secure->where($where)->value('id');
            
        } catch (\Exception $e) {
            Log::record('[ 查找投保车辆 ]:'.$e->getMessage(),'error');
            return false;
        }
        
        if($secureId){
            try {
                $this->secure->create($data,true);
            } catch (\Exception $e) {
                Log::record('[ 添加记录 ]:'.$e->getMessage(),'error');
                return false;
            }
            
            try {
                $this->secure->update(['status'=>2,'notice'=>2,'warn'=>2],['id'=>$secureId]);
            } catch (\Exception $e) {
                Log::record('[ 更新状态 ]:'.$e->getMessage(),'error');
                return false;
            }
            
        }else{
            try {
                $this->secure->create($data,true);
            } catch (\Exception $e) {
                Log::record('[ 添加记录 ]:'.$e->getMessage(),'error');
                return false;
            }
        } 
        
        return true;
    }
    
    public function del(int $id)
    {
        try {
            $this->secure->destroy($id);
        } catch (\Exception $e) {
            Log::record('[ 删除数据 ]:'.$e->getMessage(),'error');
            return false;
        }
        return true;
    }

    
    






}

